package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName Demo03
 * @Description TODO
 * @Author liang
 * @Date 2018/10/18 10:32
 * @Version 1.0
 **/
public class Demo03 {
    public static void test1(){
        User user = new User();
        long l = System.currentTimeMillis();
        for(int i=0;i < 1000000000;i++){
            user.getId();
        }
        long end = System.currentTimeMillis();
        System.out.println("普通方法执行10亿次耗时："+(end-l)+"ms");
    }
    public static void test2() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<?> clazz = Class.forName("reflection.User");
        User u = (User) clazz.newInstance();
        Method m = clazz.getDeclaredMethod("getId", null);
        long l = System.currentTimeMillis();
        for(int i=0;i < 1000000000;i++){
            m.invoke(u,null);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射执行10亿次耗时："+(end-l)+"ms");
    }
    public static void test3() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<?> clazz = Class.forName("reflection.User");
        User u = (User) clazz.newInstance();
        Method m = clazz.getDeclaredMethod("getId", null);
        m.setAccessible(true);//不执行安全检查
        long l = System.currentTimeMillis();
        for(int i=0;i < 1000000000;i++){
            m.invoke(u,null);
        }
        long end = System.currentTimeMillis();
        System.out.println("不执行安全检查反射执行10亿次耗时："+(end-l)+"ms");
    }
    public static void main(String [] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        test1();
        test2();
        test3();
    }
}
